// 创建切片
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
// 引入异步方法，拿到结果同步使用
import { getIdentifyList } from '../../api/login'
// 获取路由配置时调用的方法， 通过传入的id判断
export let myRoute = createAsyncThunk('getRoutes', async (identify) => {

    // 获取动态路由列表，此方法修改 localstorage， 会触发 app.js页面的更新和方法的重新调用
    let res = await getIdentifyList({identify:identify})
    localStorage.setItem('userRoute',JSON.stringify(res.data))
    console.log(res.data, 'res.data');
    // 生成动态菜单的配置项
    let configList = res.data.map((item) => {
        return {
            path: `/${item.path}`,
            name: item.path,
            label: item.label,
            url: `/${item.path}/index`
        }
    })
    localStorage.setItem('userConfig',JSON.stringify(configList))
    return res.data
})

// 使用获取的路由创建切片
let _localuserRoute = localStorage.getItem('userRoute')
let routerSlice = createSlice({
    name: 'routerList',
    initialState: {
        identify:0,
        username:'',
        userRoute: _localuserRoute ? JSON.parse(_localuserRoute) : []
    },
    reducers: {
        // 登录时调用的方法， 保存id
        changeRoute(state, action) {
            console.log(action.payload, 'action.payload');
            localStorage.setItem('identify',action.payload)
            state.identify = action.payload
        },
        changeUsername(state, action) {
            state.username = action.payload
            localStorage.setItem('username', action.payload)
        }
    },
    // 监听异步方法， 拿到结果后同步使用
    extraReducers: (chunk) => {
        chunk.addCase(myRoute.fulfilled,(state, action) => {
            state.userRoute = action.payload
        })
    }
})

export const { changeRoute, changeUsername } = routerSlice.actions


export default routerSlice.reducer